package com.k12.admim.utils;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;

@Component
public class RocketMQProducer {
    @Resource
    private  DefaultMQProducer defaultMQProducer;
    /**
     * 可靠同步发送（自动消息存储补偿）
     */
    public SendResult reliableSend(String topic, String tags, byte[] body) throws Exception {
        String keys = UUID.randomUUID().toString();
        Message message = new Message(topic, tags, keys, body);

        try {
            // 1. 发送消息
            SendResult result = defaultMQProducer.send(message);
            // 2. 更新状态
            return result;
        } catch (Exception e) {
            // 4. 标记失败（补偿任务会重试）
            throw e;
        }
    }

    /**
     * 发送顺序消息
     */
    public SendResult sendOrderly(String topic, String tags, byte[] body, 
                                String shardingKey) throws Exception {
        String keys = UUID.randomUUID().toString();
        Message message = new Message(topic, tags, keys, body);
        return defaultMQProducer.send(message, (mqs, msg, arg) -> {
            int index = Math.abs(arg.hashCode()) % mqs.size();
            return mqs.get(index);
        }, shardingKey);
    }

    /**
     * 发送延迟消息
     * @param delayLevel 1-18 (对应1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h)
     */
    public SendResult sendDelay(String topic, String tags, byte[] body, 
                              int delayLevel) throws Exception {
        Message message = new Message(topic, tags, body);
        message.setDelayTimeLevel(delayLevel);
        return defaultMQProducer.send(message);
    }
}